#include "stdafx.h"
#include "TPFile.h"
#include "CXml/Xml.h"
#include "TPTools.h"
#include "TPTrack.h"

CTPFile::CTPFile(void)
{}

CTPFile::~CTPFile(void)
{}

void CTPFile::Close()
{
	m_strFile.Empty();
	m_strTitle.Empty();
	m_strDestNum.Empty();

	m_Tracks.RemoveAll();
}

BOOL CTPFile::Load(LPCTSTR lpstrFile)
{
	BOOL bResult = FALSE;

	if ( NULL != lpstrFile )
	{
		using namespace JWXml;
		LPTSTR	lpszXml	= NULL;
		DWORD	dwRead	= 0;
		TPTools::GetTrackData(lpstrFile, lpszXml, dwRead);

		CXml xml;

		if ( xml.LoadXml(lpszXml) )
		{
			Close();
			{
				CXmlNodePtr pRootNode = xml.GetRoot();

				m_strFile		= lpstrFile;
				m_strTitle		= pRootNode->GetAttribute(_T("title"));
				m_strDestNum	= pRootNode->GetAttribute(_T("dest"));
			}

			{
				CXmlNodesPtr	pTrackNodes	= xml.SelectNodes(_T("//Track"));
				const LONG		lCount		= pTrackNodes->GetCount();

				CXmlNodePtr		pTrackNode;
				CTrackPtr		pTrack;
				DWORD			dwEnd = 0, dwLast = 0;

				for ( LONG l = 0; l < lCount; ++l )
				{
					pTrackNode	= (*pTrackNodes)[l];
					dwEnd		= pTrackNode->GetAttribute(_T("time"), ULONG_MAX);
					pTrack		= new TRACK;

					pTrack->index.wIndex	= (WORD)dwLast;
					pTrack->index.wLength	= (WORD)(dwEnd - dwLast);
					pTrack->sTrackTitle		= pTrackNode->GetAttribute(_T("title"));
					pTrack->lpszFileTitle	= m_strTitle;
					pTrack->lpszMediaFile	= m_strFile;

					m_Tracks.Add(pTrack);

					dwLast = dwEnd + 1;
				}
			}

			bResult = TRUE;
		}
	}

	return bResult;
}

LPCTSTR CTPFile::GetFile() const
{
	return m_strFile;
}

LPCTSTR CTPFile::GetTitle() const
{
	return m_strTitle;
}

LPCTSTR CTPFile::GetDestNum() const
{
	return m_strDestNum;
}

int CTPFile::GetTrackCount() const
{
	return m_Tracks.GetSize();
}

const TRACK* CTPFile::GetTrackByIndex(int iIndex) const
{
	const TRACK* pRet = NULL;

	if ( 0 <= iIndex && iIndex < m_Tracks.GetSize() )
	{
		pRet = m_Tracks[iIndex];
	}

	return pRet;
}

BOOL CTPFile::GetTrack(DWORD dwTime, int& iTrack, const TRACK** ppTrack) const
{
	BOOL bResult = FALSE;
	int iCount = m_Tracks.GetSize();

	for ( int i = 0; i < iCount; ++i )
	{
		if ( InTrack(dwTime, m_Tracks[i]->index) )
		{
			*ppTrack = m_Tracks[i];
			iTrack = i;
			bResult = TRUE;

			break;
		}
	}

	return bResult;
}